using System;
using System.Collections;
using HCore.IOC.Beans.Factory.Attribute.Attr;
using HCore.Unity.Behaviour;
using HCore.Unity.Manager;
using HCore.Unity.Manager.Support.Loader;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;

namespace UI.UIMenu
{
    public class ImageCardScrollViewVisual : HCoreMonoBehaviour
    {
        private const string _IMAGE_URL = "https://gitee.com/heyu.520/resource/raw/master/BigJigsawImageUrl.txt";
        [Autowired] private LoadManager mLoadManager;
        private Sprite mLoadSprite;
        [Autowired] private PrefabManager mPrefabManager;
        private ScrollRect mScrollRect;

        protected override void Awake()
        {
            base.Awake();
            mLoadSprite = mLoadManager.LoadResource<Sprite>("Images/Free Flat Download 2 Icon");
            mScrollRect = GetComponent<ScrollRect>();
        }

        // Start is called before the first frame update
        private void Start()
        {
            // 启动一个协程来请求数据，使用ResourceLoader.RequestData方法。
            // RequestTexture是一个回调方法，用于处理请求到的纹理数据。
            // new DownloadHandlerTexture(true)创建一个下载处理器，用于处理图像下载。
            // SetLoadingFillAmount是一个回调方法，用于设置加载进度。
            StartCoroutine(ResourceLoader.RequestData(new Uri(_IMAGE_URL), RequestLineImageUrl));
        }

        private IEnumerator RequestLineImageUrl(UnityWebRequest request)
        {
            // 循环读取每一行并打印在控制台
            var lines = request.downloadHandler.text.Split('\n');
            foreach (var lineUrl in lines)
            {
                var imageCardVisual = mPrefabManager.LoadPrefabComponent<ImageCardVisual>(mScrollRect.content);
                imageCardVisual.LoadingImageFill = true;
                imageCardVisual.LoadingSprite = mLoadSprite;
                imageCardVisual.LoadingColor = Color.red;
                imageCardVisual.Uri = lineUrl;
                imageCardVisual.ImageDownloadCompleteEvent += texture => imageCardVisual.SetTitle($"{texture.width} x {texture.height}");
            }

            yield return null;
            // 设置滚动矩形的垂直归一化位置为1，表示滚动视图在最顶端
            mScrollRect.verticalNormalizedPosition = 1;
        }
    }
}